package cn.tedu.egweibo2.controller;

import cn.tedu.egweibo2.mapper.UserMapper;
import cn.tedu.egweibo2.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo2.pojo.dto.UserRegDTO;
import cn.tedu.egweibo2.pojo.entity.User;
import cn.tedu.egweibo2.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;

    /**
     * 注册功能
     * 接口地址:/v1/users/reg
     * 请求方式:POST
     * 请求数据类型:application/json
     * 响应数据类型:int
     * 请求示例:
     */
    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        log.debug("userRegDTO = " + userRegDTO);
        UserVO userVO = userMapper.selectUserByName(userRegDTO.getUsername());
        if(userVO != null){
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        userMapper.insertUser(user);
        return 1;
    }

    /**
     * 登录功能
     * 接口地址:/v1/users/login
     * 请求方式:POST
     * 请求数据类型:application/json
     * 响应数据类型:int
     */
    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userLoginDTO = " + userLoginDTO);
        UserVO userVO = userMapper.selectUserByName(userLoginDTO.getUsername());
        if(userVO == null){
            return 3;
        }else if(!userVO.getPassword().equals(userLoginDTO.getPassword())){
            return 2;
        }
        session.setAttribute("user", userVO);
        return 1;
    }

    /**
     * 获取当前用户
     * 接口地址:/v1/users/currentUser
     * 请求方式:GET
     * 请求数据类型:application/x-www-form-urlencoded
     * 响应数据类型:userVO
     */
    @ApiOperation(value = "获取当前用户")
    @GetMapping("currentUser")
    public UserVO currentUser(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        return userVO;
    }

    /**
     * 退出登录功能
     * 接口地址:/v1/users/logout
     * 请求方式:GET
     * 请求数据类型:application/x-www-form-urlencoded
     * 响应数据类型:见响应参数
     */
    @ApiOperation(value = "退出登录功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }
}
